﻿using BaoVeThanhDia.Buttons;
using BaoVeThanhDia.Sound;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Navigation;

namespace BaoVeThanhDia.Introduction
{
    public partial class MenuIntroduction : PhoneApplicationPage
    {
        public static ContentManager contentManager;
        GameTimer timer;
        SpriteBatch spriteBatch;
        string trangthai;
        Texture2D BackGround;
        List<Button> buttons;
        Vector2 start, curtouch, Dolech;
        int sotrang;
        MonsterIntro monsterIntro;
        TowerIntro towerIntro;
        CustomSoundEffect click;
        SpriteFont font;
        bool isLoaded;
        private BackgroundWorker bw = new BackgroundWorker();
        public MenuIntroduction()
        {
            InitializeComponent();
            contentManager = (Application.Current as App).Content;
            // Create a timer for this page
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;
            //todo
            #region OGG
            isLoaded = false;
            bw.WorkerReportsProgress = true;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            bw.RunWorkerAsync();
            #endregion

            click = new CustomSoundEffect("sounds/effect/Click_Button");
            monsterIntro = new MonsterIntro();
            towerIntro = new TowerIntro();
            sotrang = 0;
            trangthai = "menu";
            Dolech = new Vector2(0, 0);
            buttons = new List<Button>();
            buttons.Add(new Button("gioithieu", "images/Introduction/gioithieu", new Vector2(82, 120), new Vector2(0, 0), new Vector2(280, 236), 1));
            buttons.Add(new Button("tancong", "images/Introduction/ribbon", new Vector2(460, 120), new Vector2(0, 0), new Vector2(355, 90), 0.6f));
            buttons.Add(new Button("", "images/Introduction/tancong", new Vector2(510, 137), new Vector2(0, 0), new Vector2(220, 57), 0.5f));
            buttons.Add(new Button("phongthu", "images/Introduction/ribbon", new Vector2(460, 260), new Vector2(0, 0), new Vector2(355, 90), 0.6f));
            buttons.Add(new Button("", "images/Introduction/phongthu", new Vector2(507, 277), new Vector2(0, 0), new Vector2(249, 54), 0.5f));
            buttons.Add(new Button("trolai", "images/Introduction/trolai", new Vector2(610, 400), new Vector2(0, 0), new Vector2(228, 100), 0.5f));
        }
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            // Perform a time consuming operation and report progress.
            // System.Threading.Thread.Sleep(50);
            //   worker.ReportProgress()
            AudioManager.LoadSounds("song_introduction.ogg");
        }
        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            isLoaded = true;
            if (MainPage.isNen) AudioManager.PlaySound("song_introduction.ogg", true);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (MapAndUpgrade.MapAndUpgrade.contentManager != null) MapAndUpgrade.MapAndUpgrade.contentManager.Unload();
            // Set the sharing mode of the graphics device to turn on XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);

            // TODO: use this.content to load your game content here
            click.Load(contentManager);
            Dolech = new Vector2(0, 0);
            curtouch = new Vector2(0, 0);
            start = new Vector2(0, 0);
            foreach (Button button in buttons)
            {
                button.Load(contentManager);
            }
            monsterIntro.Load(contentManager);
            towerIntro.Load(contentManager);
            if (MainPage.isNen) AudioManager.PlaySound("song_introduction.ogg", true);
            font = contentManager.Load<SpriteFont>("fonts/WaveFont");
            timer.Start();

            base.OnNavigatedTo(e);
        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            AudioManager.StopSound("song_introduction.ogg");
            // Stop the timer
            timer.Stop();

            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

            base.OnNavigatedFrom(e);
        }
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            click.Play();
            if (!trangthai.Equals("menu"))
            {
                curtouch = new Vector2(0, 0);
                start = new Vector2(0, 0);
                trangthai = "menu";
                Dolech = new Vector2(0, 0);
                e.Cancel = true;
            }
        }
        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            // TODO: Add your update logic here
            if (isLoaded)
            {
                TouchCollection touchs = TouchPanel.GetState();
                foreach (TouchLocation touch in touchs)
                {
                    if (touch.State == TouchLocationState.Pressed)
                    {
                        start = touch.Position;
                        curtouch = touch.Position;
                    }
                    if (touch.State == TouchLocationState.Moved)
                    {
                        Dolech += touch.Position - curtouch;
                        curtouch = touch.Position;
                        if (Dolech.X > 0) Dolech.X = 0;
                        if (Dolech.Y > 0) Dolech.Y = 0;
                        if (trangthai.Equals("tancong"))
                        {
                            if (-Dolech.X + 800 > 3420) Dolech.X = 800 - 3420;
                            Dolech.Y = 0;
                        }
                        else if (trangthai.Equals("phongthu"))
                        {
                            if (-Dolech.X + 800 > 1040) Dolech.X = 800 - 1040;
                            Dolech.Y = 0;
                        }
                        if (trangthai.Equals("menu"))
                        {
                            foreach (Button button in buttons)
                            {
                                button.isTouch(curtouch);
                            }
                        }
                        else if (trangthai.Equals("gioithieu"))
                        {
                            buttons[5].isTouch(curtouch);
                        }
                    }
                    if (touch.State == TouchLocationState.Released)
                    {
                        curtouch = touch.Position;
                        if (trangthai.Equals("menu"))
                        {
                            #region xử lí các nút bấm trong menu
                            foreach (Button button in buttons)
                            {
                                if (button.isTouch(curtouch))
                                {
                                    click.Play();
                                    button.setTouch(false);
                                    if (button.getName().Equals("trolai")) NavigationService.GoBack();
                                    else if (button.getName().Equals("phongthu")) trangthai = "phongthu";
                                    else if (button.getName().Equals("tancong")) trangthai = "tancong";
                                    else if (button.getName().Equals("gioithieu")) { trangthai = "gioithieu"; sotrang = 0; }
                                }
                            }
                            #endregion
                        }
                        else if (trangthai.Equals("gioithieu"))
                        {
                            #region xử lí nút bấm trong giới thiệu
                            if (curtouch.X <= start.X - 100 && Math.Abs(curtouch.Y - start.Y) <= Math.Abs(curtouch.X - start.X)) sotrang++;
                            if (curtouch.X >= start.X + 100 && Math.Abs(curtouch.Y - start.Y) <= Math.Abs(curtouch.X - start.X)) sotrang--;
                            if (sotrang < 0) sotrang = 0;
                            if (sotrang > 6) sotrang = 6;
                            if (buttons[5].isTouch(curtouch))
                            {
                                click.Play();
                                buttons[5].setTouch(false);
                                trangthai = "menu";
                            }
                            #endregion
                        }
                        else if (trangthai.Equals("tancong"))
                        {
                            #region xử lí trong thông tin quái
                            if (Vector2.Distance(start, curtouch) <= 30)
                            {
                                monsterIntro.isTouch(curtouch, Dolech, contentManager);
                            }
                            #endregion
                        }
                        else if (trangthai.Equals("phongthu"))
                        {
                            #region xử lí trong thông tin tháp
                            if (Vector2.Distance(start, curtouch) <= 30)
                            {
                                towerIntro.isTouch(curtouch, Dolech, contentManager);
                            }
                            #endregion
                        }
                    }
                }
            }
        }
        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.Black);
            if (trangthai.Equals("menu"))
            {
                BackGround = contentManager.Load<Texture2D>("images/Introduction/background");
            }
            else if (trangthai.Equals("gioithieu"))
            {
                BackGround = contentManager.Load<Texture2D>("images/Introduction/" + sotrang.ToString());
            }
            else
            {
                BackGround = contentManager.Load<Texture2D>("images/Introduction/bg2");
            }
            // TODO: Add your drawing code here
            spriteBatch.Begin();

            spriteBatch.Draw(BackGround, new Vector2(0, 0), new Rectangle(0, 0, trangthai.Equals("gioithieu") ? 800 : 200, trangthai.Equals("gioithieu") ? 480 : 120), Color.White, 0f, Vector2.Zero, trangthai.Equals("gioithieu") ? 1 : 4, SpriteEffects.None, 0f);
            if (isLoaded)
            {
                if (trangthai.Equals("menu"))
                {
                    foreach (Button button in buttons)
                    {
                        button.Draw(spriteBatch, new Vector2(0, 0));
                    }
                }
                else if (trangthai.Equals("gioithieu"))
                {
                    buttons[5].Draw(spriteBatch, new Vector2(0, 0));
                }
                else if (trangthai.Equals("tancong"))
                {
                    monsterIntro.Draw(spriteBatch, Dolech);
                }
                else if (trangthai.Equals("phongthu"))
                {
                    towerIntro.Draw(spriteBatch, Dolech);
                }
            }
            else spriteBatch.DrawString(font, "Loading . . .", new Vector2(630, 450), Color.White);
            spriteBatch.End();
        }
    }
}